﻿using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;
using System;
using System.Collections.Generic;
using System.Text;

namespace iTool.SQL.Analysis.WhereClause
{
    public class SqlLikeBooleanExpressionAnalysis : SqlAnalysisBase
    {
        public SqlLikeBooleanExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            //StringBuilder where = base.GetWhereBuilder();
            var expression = (SqlLikeBooleanExpression)base.CodeObject;

            var groupWheres = base.GetGroupWhere();
            WhereOptions whereOptions = new WhereOptions();
            SubWhereOptions sub = null;
            whereOptions.Parent = base.WhereOptions;

            if (base.WhereOptions is GroupWhereOptions group)
            {
                group.Wheres.Add(whereOptions);
            }
            else if (base.WhereOptions is SubWhereOptions)
            {
                sub = (SubWhereOptions)base.WhereOptions;
                // sub.Wheres[^1] is group
                if (sub.Wheres.Count == 0)
                {
                    sub.Wheres.Add(new GroupWhereOptions());
                }
                sub.Wheres[^1].Wheres.Add(whereOptions);
            }
            else
            {
                groupWheres[^1].Wheres.Add(whereOptions);
            }

            whereOptions.ComparisonBooleanExpressionType = expression.HasNot ? ComparisonBooleanExpressionType.IsNotLike : ComparisonBooleanExpressionType.IsLike;

            base.Next(beforeAction: (index, _, analysis) =>
            {
                //string nbsp = _ is SqlLiteralExpression ? " " : string.Empty;
                //if (index == 1)
                //    where.Append(expression.HasNot ? " not like" + nbsp : " like" + nbsp);
                return true;
            }, whereOptions: whereOptions);
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
